package upload

import (
	"x-admin/backend/config"
	"x-admin/backend/internal/middleware"
	"x-admin/backend/pkg/storage"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// RegisterRoutes 注册文件上传路由
func RegisterRoutes(r *gin.RouterGroup, db *gorm.DB, cfg *config.Config) {
	// 创建存储驱动
	var storageDriver storage.StorageDriver
	switch cfg.Storage.Driver {
	case "local":
		storageDriver = storage.NewLocalStorage(cfg.Storage.LocalDir, cfg.Storage.BaseURL)
	case "aliyun":
		// TODO: 实现阿里云OSS存储驱动
		// storageDriver = storage.NewAliyunOSSStorage(cfg.Storage.AliyunOSS)
		storageDriver = storage.NewLocalStorage(cfg.Storage.LocalDir, cfg.Storage.BaseURL)
	default:
		storageDriver = storage.NewLocalStorage("uploads", "http://localhost:8080/uploads")
	}

	// 创建存储管理器配置
	uploadConfig := storage.GetDefaultImageConfig()
	uploadConfig.HashAlgorithm = cfg.Storage.HashAlgorithm

	// 创建存储管理器
	storageManager := storage.NewManager(storageDriver, uploadConfig)

	// 创建依赖
	repo := NewRepository(db)
	service := NewService(repo, storageManager)
	handler := NewHandler(service)

	// 创建权限路由组
	uploadGroup := middleware.NewPermissionGroup(r.Group("/upload"), db)
	{
		uploadGroup.POST("", "", handler.Upload)                                // 上传文件
		uploadGroup.POST("/delete", "upload:delete", handler.Delete)            // 删除文件
		uploadGroup.POST("/batch-delete", "upload:delete", handler.BatchDelete) // 批量删除文件
		uploadGroup.GET("/config", "upload:config", handler.GetConfig)          // 获取上传配置
	}

	// 文件管理路由
	filesGroup := middleware.NewPermissionGroup(r.Group("/upload/files"), db)
	{
		filesGroup.GET("", "upload:list", handler.List)        // 获取文件列表
		filesGroup.GET("/:id", "upload:view", handler.GetByID) // 获取文件详情
	}
}
